package com.neusoft.controller;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.po.EmpPO;
import com.neusoft.po.LoginPO;
import com.neusoft.response.Result;
import com.neusoft.service.LoginService;
import com.neusoft.util.MD5EncryptionUtil;
import com.neusoft.util.MailUtil;
import com.neusoft.util.PasswordGenerator;
import com.neusoft.util.TokenUtil;
import com.neusoft.vo.ResetVO;

@CrossOrigin
@RestController
public class LoginHandler {

	@Autowired
	private LoginService s;

	@PostMapping("/login")
	public Result login(@RequestBody LoginPO po) {
		System.out.println("尝试登陆" + po);
		EmpPO poo = s.loginCheck(po);
		if (poo != null && poo.getState() == 1) {
			String token = TokenUtil.getToken(Long.valueOf(poo.getEmpno()));
			LoginPO pooo = new LoginPO();
			pooo.setEmpno(poo.getEmpno());
			pooo.setToken(token);
			pooo.setDeptno(poo.getDeptno());
			pooo.setRoot(poo.getRoot());
			pooo.setEname(poo.getEname());
			return new Result(100, "请求成功", pooo);
		} else {
			return new Result(101, "账号或密码不存在", null);
		}
	}

//	通过邮箱发送随机密码
	@PostMapping("/reset")
	public int resetPassword(@RequestBody ResetVO vo) {
//		1.查询该邮箱是否存在
		System.out.println(vo);
		if (s.selectEmail(vo) != null) {
//			2.存在则 生成随机密码存入数据库，并发送邮件，返回1
			String pwd = PasswordGenerator.generatePassword();
			String databasePwd = MD5EncryptionUtil.encrypted(pwd);
			System.out.println("databasePwd:" + databasePwd);
			vo.setDatabasePwd(databasePwd);
			Set<String> set = new HashSet<>();
			set.add(vo.getEmail());
			System.out.println(MailUtil.sendEmail(set, "来自`kk人挺好`的密码重置邮件", "您好！这是来自kk人挺好的密码重置邮件，您的新密码是：" + pwd));
			return s.updatePwd(vo);
		} else {
//		3.不存在则返回0
			return 0;
		}
	}

}
